package com.lqk.observer.improve;

import com.lqk.observer.CurrentConditions;

import java.util.ArrayList;

/**
 * @author lqk
 * @date 2021/12/10 10:30
 *
 * 核心类：
 *  1. 包含最新的天气情况信息
 *  2. 含有观察者集合，使用ArrayList进行管理
 *  3. 当数据有更新时，就主动的遍历 ArrayList，通知所有的接入方就看到最新的数据
 */
public class WeatherData implements Subject {
    private float temperatrue;
    private float pressure;
    private float humidity;
    private ArrayList<Observer> observers;

    public WeatherData() {
        observers = new ArrayList<>();
    }

    public float getTemperature() {
        return temperatrue;
    }

    public float getPressure() {
        return pressure;
    }

    public float getHumidity() {
        return humidity;
    }

    public void dataChange() {
        notifyObservers();
    }

    // 当数据有更新时，就调用 setData
    public void setData(float temperature, float pressure, float humidity) {
        this.temperatrue = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        dataChange();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void remove(Observer o) {
        if (observers.contains(o)){
            observers.remove(o);
        }
    }

    @Override
    public void notifyObservers() {
        observers.stream().forEach(observer -> {
            observer.update(getTemperature(), getPressure(), getHumidity());
        });
    }
}
